package com.snails.app.base.mvp.view;

import android.os.Bundle;
import android.view.Gravity;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.StringRes;

import com.snails.app.R;
import com.snails.app.base.BaseFragment;
import com.snails.app.base.mvp.presenter.AbstractPresenter;
import com.snails.app.utils.ToastUtil;
import com.snails.ui.dialog.LoadingDialog;

/**
 * @author lawrence
 * @date 2019-04-26 18:11
 */
public abstract class BaseMvpFragment<P extends AbstractPresenter>
        extends BaseFragment implements AbstractView<P> {

    @Nullable protected P mPresenter = null;
    @Nullable LoadingDialog mLoadDialog = null;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        this.mPresenter = newPresenter();
        if (this.mPresenter != null) this.mPresenter.onAttachV(this);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (this.mPresenter != null) mPresenter.onDetachV();
    }

    @Override
    public void onCompleted(@Nullable Bundle bundle) { }

    @Override
    public void showLoading() {
        if (this.mCtx != null && !this.mCtx.isFinishing()) {
            if (this.mLoadDialog == null) {
                this.mLoadDialog = new LoadingDialog.Builder()
                        .message(this.mCtx, R.string.a_core_dialog_loading)
                        .build(this.mCtx);
            }
            if (!this.mLoadDialog.isShowing()) this.mLoadDialog.show();
        }
    }
    @Override
    public void showLoading(String message) {
        if (this.mCtx != null && !this.mCtx.isFinishing()) {
            if (this.mLoadDialog == null) {
                this.mLoadDialog = new LoadingDialog.Builder()
                        .message(message).build(this.mCtx);
            } else {
                this.mLoadDialog.setMessage(message);
            }
            if (!this.mLoadDialog.isShowing()) this.mLoadDialog.show();
        }
    }
    @Override
    public void closeLoading() {
        if (this.mLoadDialog != null && this.mLoadDialog.isShowing()) {
            this.mLoadDialog.dismiss();
        }
        this.mLoadDialog = null;
    }

    @Override
    public void showToast(String message) {
        ToastUtil.instance().showText(message, Toast.LENGTH_SHORT, Gravity.CENTER);
    }

    @Override
    public void showToast(@StringRes int resId) {
        ToastUtil.instance().showText(resId, Toast.LENGTH_SHORT, Gravity.CENTER);
    }

}
